package kr.hyunist.memoappproject;

import java.util.ArrayList;
import java.util.Collections;

import kr.hyunist.memoappproject.BaseAdapter.MyMemoAppAdapter;
import kr.hyunist.memoappproject.DAO.MyMemoAppDAO;
import kr.hyunist.memoappproject.DTO.*;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
	BackPressCloseHandler backPressCloseHandler;
	ArrayList<MyMemo> arList;
	MyMemoAppAdapter Adapter;
	MyMemo mMemo;
	ListView list;
	
	MyMemoAppDAO Dao;

	Intent in = null;
	
	static final int MemoIn = 0;
	static final int SettinIn = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		backPressCloseHandler = new BackPressCloseHandler(this);

		Dao = MyMemoAppDAO.open(MainActivity.this);
		arList = Dao.selectMemoList();

		Adapter = new MyMemoAppAdapter(this, R.layout.memoappcontent, arList);

		list = (ListView) findViewById(R.id.memoapplist);
		list.setAdapter(Adapter);
		list.setOnItemClickListener(mClickListener);
		list.setOnItemLongClickListener(mLongClickListener);

	}

	//리스트에서 메모 하나 선택했을때 이벤트 처리
	OnItemClickListener mClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// id를 기준으로 select
			final int pos = position;

			boolean SelectMemo = Dao.selectMemo(arList.get(pos).getId());
			in = new Intent(MainActivity.this, MemoWrite.class);
			in.putExtra("IdIn", arList.get(pos).getId());
			in.putExtra("TitleIn", arList.get(pos).getTitle());
			in.putExtra("ContentIn", arList.get(pos).getContents());
			startActivityForResult(in, MemoIn);

		}

	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == MemoIn) {
			if (resultCode == RESULT_OK) {
				/*
				 * 리스트뷰가 arrayList로 되어있다면 arrayList를 clear한 후
				 * 
				 * 다시 디비내용을 add시킨 다음 notifyDataSetChanged();
				 */
				arList.clear();
				Adapter.notifyDataSetInvalidated();

				arList.addAll(Dao.selectMemoList());
				Adapter.notifyDataSetChanged();

			} else {
				Toast.makeText(MainActivity.this, "사용자가 입력을 취소!",
						Toast.LENGTH_SHORT).show();
			}
		}

	}

	//롱클릭시 삭제 이벤트 처리
	OnItemLongClickListener mLongClickListener = new OnItemLongClickListener() {

		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view,
				int position, long id) {
			final int pos = position;

			AlertDialog.Builder alg = new AlertDialog.Builder(MainActivity.this);
			alg.setTitle("삭제");
			alg.setMessage("메모가 삭제 됩니다. 현재ID : " + arList.get(pos).getId());
			alg.setNegativeButton("취소", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					Toast.makeText(MainActivity.this, "삭제 취소!",
							Toast.LENGTH_SHORT).show();
				}

			});
			alg.setPositiveButton("확인", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					boolean DeleteMemo = Dao.deleteMemo(arList.get(pos).getId());
					String res = DeleteMemo ? "삭제 완료!" : "삭제 실패!";

					arList.clear();
					Adapter.notifyDataSetInvalidated();
					arList.addAll(Dao.selectMemoList());
					Adapter.notifyDataSetChanged();

					Toast.makeText(MainActivity.this, res, Toast.LENGTH_SHORT)
							.show();

				}

			});
			alg.show();

			return true;
		}

	};

	// 액션바 글쓰기 버튼 전개
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.actionbarmenuwrite, menu);
		return true;

	}

	// 액션바 글쓰기 버튼 선택시 동작
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.actionbarwritebtn:
			in = new Intent(this, MemoWrite.class);
			startActivityForResult(in, MemoIn);
			break;
		
		case R.id.actionbarsetting:
			in = new Intent(this, MemoSetting.class);
			startActivityForResult(in, SettinIn);
			break;
		}
		return true;
	}

	//메뉴 아이템 이벤트 처리
	public void mOnClick(MenuItem item) {
		
		switch (item.getItemId()) {
		case R.id.titlearray:
			MyComparatorTitle mct = new MyComparatorTitle();
			Collections.sort(arList, mct);
			Adapter.notifyDataSetChanged();
			Toast.makeText(MainActivity.this, "제목정렬성공", 0).show();
			
			break;

		case R.id.contentarray:
			
			MyComparatorContent mcc = new MyComparatorContent();
			Collections.sort(arList, mcc);
			Adapter.notifyDataSetChanged();
			Toast.makeText(MainActivity.this, "내용정렬성공", 0).show();
			
			break;
			
		case R.id.datearray:
			
			MyComparatorDate mcd = new MyComparatorDate();
			Collections.sort(arList, mcd);
			Adapter.notifyDataSetChanged();
			Toast.makeText(MainActivity.this, "시간정렬성공", 0).show();
			
			break;	
			
		case R.id.menusearch:
			final EditText searchEt = new EditText(this);
			AlertDialog.Builder sDlg = new AlertDialog.Builder(this);
			
			sDlg.setTitle("검색어를 입력").setCancelable(false)
					.setIcon(R.drawable.memoicon).setView(searchEt)
					.setPositiveButton("확인", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							
							//arList = Dao.searchSelected(searchEt.getText().toString());
					
							arList.clear();
							boolean result = arList.addAll(Dao.searchSelected(searchEt.getText().toString()));
							Adapter.notifyDataSetChanged();
							
							if(result){
								Toast.makeText(MainActivity.this, "검색성공", Toast.LENGTH_SHORT).show();
							} else {
								arList.addAll(Dao.selectMemoList());
								Adapter.notifyDataSetChanged();
								Toast.makeText(MainActivity.this, "검색결과없음", Toast.LENGTH_SHORT).show();
							}
														
						}
						
					})
					.setNegativeButton("취소", new OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {							
						}
						
					}).show();
			break;
		}
	}

	//백버튼 두번 눌러야 중지
	@Override
	public void onBackPressed() {
		backPressCloseHandler.onBackPressed();
	}

}
